package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.IApLikeBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dto.BehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApLikeBehaviorServiceImpl implements IApLikeBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult like(BehaviorDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getArticleId() == null || checkParam(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 是否登录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        // 3. 点赞保存数据
        String key = "LIKE-BEHAVIOR-" + dto.getArticleId().toString();
        String hashKey = apUser.getId().toString();

        if (dto.getOperation() == 0){
            Object object = cacheService.hGet(key, apUser.getId().toString());
            if (object != null){
                ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"禁止重复点赞");
            }
            // 保存当前key
            log.info("保存当前key：{}，{}，{}",key, hashKey, JSON.toJSONString(dto));
            cacheService.hPut(key, hashKey, JSON.toJSONString(dto));
            mess.setAdd(1);
        }else {
            // 删除当前key
            log.info("删除当前key：{}，{}",key, hashKey);
            cacheService.hDelete(key, hashKey);
            mess.setAdd(-1);
        }
        //发送消息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    private boolean checkParam(BehaviorDto dto) {
        return dto.getType() < 0 || dto.getType() > 2 || dto.getOperation() < 0 || dto.getOperation() > 1;
    }
}
